package com.wanma.thread;
/**
 * synchronized锁
 * @author Administrator
 *
 */
public class ThreadDemo1 {
	/*
	 * 数据错乱
	 */
	public static void main(String[] args) {
		
		Res res = new Res();
		InpThread InpThread = new InpThread(res);
		ReadThread ReadThread = new ReadThread(res);
		InpThread.start();
		ReadThread.start();
	}
	
}
class  Res{
	 String name;
  	 String sex;
	 public boolean flag = false;
}
//写入线程
class InpThread extends Thread{
	private Res res;
	public InpThread(Res res) {
		this.res = res;
	}
	@Override
	public void run() {
		int count = 0;
		while (true) {
			synchronized (res) {
				if(res.flag){
					try {
						res.wait();
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
				if(count == 0){
					res.name = "余胜军";
					res.sex = "男";
				}else{
					res.name = "小红";
					res.sex = "女";
				}
				count = (count+1) %2;
				res.flag = true;
				res.notify();
			}
			
		}
	}
}
//读取线程
class ReadThread extends Thread{
	private Res res;
	public ReadThread(Res res) {
		this.res = res;
	}
	@Override
	public void run() {
		while(true){
			synchronized(res){
				if(!res.flag){
					try {
						res.wait();
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
				System.out.println(res.name + "---/t"+ res.sex);
				res.flag = false;
				res.notify();
			}
		}
	}
}
